#pragma once
#include <iostream>
#include <string>
#include"Log.hpp"

std::string opers="+-*/%";

extern Log lg;

enum{
    DivZero=1,
    ModZero,
    Unknown
};

class Task   //一个线程负责一次的数据传输
{
public:
    Task()
    {}
    Task(int sockfd,std::string clientip,uint16_t clientport) : sockfd_(sockfd), clientport_(clientport), clientip_(clientip)
    {}
    void run()
    {
        Service(sockfd_,clientport_,clientip_);
    }
    void operator ()()
    {
        run();
    }
    // std::string GetResult()   //r: a+b=c[code:1]
    // {
    //     std::string r = std::to_string(data1_);
    //     r += oper_;
    //     r += std::to_string(data2_);
    //     r += "=";
    //     r += std::to_string(result_);
    //     r += "[code: ";
    //     r += std::to_string(exitcode_);
    //     r += "]";

    //     return r;
    // }
    // std::string GetTask()     //r:  a+b=?
    // {
    //     std::string r = std::to_string(data1_);
    //     r += oper_;
    //     r += std::to_string(data2_);
    //     r += "=?";
    //     return r;
    // }
    ~Task()
    {
    }
private:
    void Service(int sockfd,uint16_t clientport,std::string clientip)
    {
        char buffer[1024];
        int n = read(sockfd, buffer, 1024); // 收，阻塞模式
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "client say# " << buffer << std::endl;
            std::string echo_string = "tcpserver echo# ";
            echo_string += buffer;

            write(sockfd, echo_string.c_str(), echo_string.size()); // 发
        }
        else if (n == 0) // 连接已关闭（TCP 对端调用了 close()）
        {
            lg(Info, "%s:%d quit, server close sockfd: %d", clientip.std::string::c_str(), clientport, sockfd);
        }
        else // 出错，检查 errno
        {
            lg(Warning, "readsss error, sockfd: %d, client ip: %s, client port: %d", sockfd, clientip.std::string::c_str(), clientport);
        }
        close(sockfd);
    }

private:
    int sockfd_;
    uint16_t clientport_;
    std::string clientip_;
};